local args = ngx.req.get_uri_args()

local act_id = args.act_id

if nil == act_id then
    ngx.say('{"code":10000,"message":"act_id不能为空","data":{"allowed":false,"type":"can-not-found","surplus_times":0}}')
    return
end

local vote_token = args.vote_token

if nil == vote_token then
    ngx.say('{"code":10000,"message":"vote_token不能为空"}')
    return
end

local redis_client = require "lib.redis"
local redis = redis_client:new()

--开始投票
local rules = redis:hmget('rules:'..act_id, 'limit_type', 'limit_times', 'start_at', 'end_at', 'is_paused')

if nil == rules then
    ngx.say('{"code":10000,"message":"活动不存在","data":{"allowed":false,"type":"not-found","surplus_times":0}}')
    return
end

local is_paused = tonumber(rules[5])

--验证活动是否暂停
if is_paused == 1 then
    ngx.say('{"code":10000,"message":"活动已暂停","data":{"allowed": false,"type":"paused","surplus_times":0}}')
    return
end

local time = ngx.time()
local start_at = rules[3] or 0
local end_at = rules[4] or (time + 1)

--验证活动时间
if time > tonumber(end_at) then
    ngx.say('{"code":10000,"message":"活动已经结束","data":{"allowed":false,"type":"act-end","surplus_times":0}}')
    return
end

if time < tonumber(start_at) then
    ngx.say('{"code":10000,"message":"活动还未开始","data":{"allowed":false,"type":"act-not-start","surplus_times":0}}')
    return
end

-- 验证参数
local user_id = args.uid

if nil == user_id then
    ngx.say('{"code":10000,"message":"您没有登录","data":{"allowed":false,"type":"no-login","surplus_times":0}}')
    return
end

local user, err = redis:hget('app:uid:'..act_id, user_id)

-- 验证是否登录
if nil == user then
    ngx.say('{"code":10000,"message":"您没有登录","data":{"allowed":false,"type":"no-login","surplus_times":0}}')
    return
end
-- 判断验签是否正确
-- if vote_token ~= user then
--     ngx.say('{"code":10001,"message":"验签不匹配","data":{"allowed":false,"type":"no-login","surplus_times":0}}')
--     return
-- end

-- local ways = args.ways
-- -- 删除验签
-- if ways ~= "wechat" then
--     redis:hset('app:uid:'..act_id, user_id, '')
-- end
-- 验证投票次数，防刷票
local times_key = "times:"..act_id..":"..user_id
local mode = rules[1]
local limit_times = tonumber(rules[2])
local surplus_times = 0

if mode == 'day' then
    local times_of_everday = redis:hget(times_key, ngx.today())
    local t = tonumber(times_of_everday) or 0
    surplus_times = limit_times - t
    if t >= limit_times then
        ngx.say('{"code":10000,"message":"您今天的抽奖次数已用完","data":{"allowed":false,"type":"no-times","surplus_times":', surplus_times, '}}')
        return
    end
else
    local times_of_life = redis:hget(times_key, 'total')
    local t = tonumber(times_of_life) or 0
    surplus_times = limit_times - t
    if t >= limit_times then
        ngx.say('{"code":10000,"message":"您的抽奖次数已用完","data":{"allowed":false,"type":"no-times","surplus_times":', surplus_times, '}}')
        return
    end
end

ngx.say('{"code":200,"message":"success","data":{"allowed":true,"type":null,"surplus_times":', surplus_times, '}}')
